package com.youxin.JobCenter;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.youxin.foundation.db.redis.RedisClusterCommand;
import com.youxin.jobcenter.service.PayStatusCheckService;
/**
 * @ClassName: PayStatusCheck 
 * @Description: 支付状态检查任务 
 * @author yingde.cao
 * @date 2017年12月19日 下午3:42:04 
 *
 */
@Component
public class PayStatusCheck implements Serializable {
	/** 
	 * @Fields serialVersionUID : TODO
	 */ 
	private static final long serialVersionUID = -8160728086098453948L;
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PayStatusCheck.class);
	@Autowired
	public PayStatusCheckService payStatusCheckService;
	private static 	String LOCKSTAMP_KEY = "PAY_STATUS_CHECK_JOB";
	//超时时间
	private static 	long DEFAULT_TIMEOUT = 10;


	/**
	 * @Title: execute 
	 * @Description: redis锁机制处理任务调度
	 * @param 
	 * @return void
	 * @throws
	 */
	public void execute()  {
		long lock = 0;
		while (lock != 1) {
			//系统时间+超时时间+1
			long timestamp = System.currentTimeMillis() + DEFAULT_TIMEOUT + 1;
			//如果不存在，则 SET, 1表示成功，获取锁，0表示失败，未获取，多台server仅有一个会获取锁
			lock = RedisClusterCommand.setnx(LOCKSTAMP_KEY, timestamp + "");
			logger.warn("lock time:"+lock);
			//如果自己获取锁，或者原有的master已经超时，则标记自己为master，同时改变锁的超时时间
			String lockstamp = RedisClusterCommand.get(LOCKSTAMP_KEY);
			//将给定 key 的值设为 value ，并返回 key 的旧值
			String oldLockstamp = RedisClusterCommand.getSet(LOCKSTAMP_KEY, timestamp + "");
			logger.warn("lockstamp:"+lockstamp+",oldLockstamp:"+oldLockstamp);
			if (lock == 1
					|| (System.currentTimeMillis() > Long.parseLong(lockstamp) 
					&& System.currentTimeMillis() > Long.parseLong(oldLockstamp))) {
				logger.warn("标记为 master, 任务准备执行...");
				break;
			} else {
				try {
					logger.warn("标记自己为slave，并等待!");
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					logger.warn("Failed to release lock"+ e);
				}
			}

		}
		logger.warn("=========Job start=========");
		payStatusCheckService.selectFailurePayOrderList();
		logger.warn("=========Job end=========");
		//如果未超时，则释放锁
		if (System.currentTimeMillis() < Long.parseLong(RedisClusterCommand.get(LOCKSTAMP_KEY))) {
			RedisClusterCommand.delete(LOCKSTAMP_KEY);
		}
	}
}	
